from werkzeug.exceptions import HTTPException

from app import create_app
from app.base.baseError import APIException
from app.libs.error_code import ServerError
from app.libs.init import celery
from flask_limiter import Limiter

from flask_limiter.util import get_remote_address

app = create_app()
celery.conf.update(app.config)

# 限制ip访问频率
limiter = Limiter(app=app, key_func=get_remote_address, default_limits=['60 per minute', '3000 per hour'],
                  storage_uri=app.config.get('LIMITER_UIR'))


@app.errorhandler(429)
def error_429(e):
    return APIException(msg='访问频繁，请稍后再试')


@app.errorhandler(Exception)
def framework_error(e):
    if isinstance(e, APIException):
        return e
    if isinstance(e, HTTPException):
        code = e.code
        msg = e.description
        error_code = 1007
        return APIException(msg, code, error_code)
    else:
        if app.debug is True:
            raise e
        app.logger.error(f"错误：{e}")
        return ServerError()


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=app.debug)
    # server = pywsgi.WSGIServer(('0.0.0.0', 5000), app)
    # server.serve_forever()
